<template>
  <div class="ipicker">
    <I-Input
      v-model="fieldValue"
      is-link
      readonly
      :required="required"
      :rules="rules"
      :label="label"
      :input-align="inputAlign"
      :placeholder="placeholder"
      @click="showPickerClick"
    ></I-Input>
    <van-popup v-model:show="showPicker"  position="bottom">
      <van-picker
        :columns="formatColumns"
        :title="title"
        :default-index="defaultIndex"
        @cancel="showPicker = false"
        @confirm="onConfirm"
      />
    </van-popup>
  </div>
</template>
  
<script setup name="IPickerComponent">
import { ref, watch, computed } from 'vue'
import { showToast } from 'vant'

const fieldValue = ref('')
const showPicker = ref(false)

const emit = defineEmits(['update:modelValue', 'change'])
const props = defineProps({
  label: {
    type: String,
    default: ''
  },
  title: {
    type: String,
    default: '标题'
  },
  required: {
    type: Boolean,
    default: false
  },
  modelValue: {
    type: [String, Number],
    required: true
  },
  rules: {
    type: Array,
    default: () => []
  },
  inputAlign: {
    type: String,
    default: 'left'
  },
  placeholder: {
    type: String,
    default: '请选择'
  },
  columns: {
    type: Array,
    default: () => []
  },
  columnsFieldNames: {
    type: Object,
    default: () => ({ text: 'text', value: 'value', children: 'children' })
  }
})

// 格式化列数据
const formatColumns = computed(() => {
  return props.columns.map((item) => ({
    text: item[props.columnsFieldNames.text] || item[props.columnsFieldNames.label] || item.city,
    value: item[props.columnsFieldNames.value] || item.code
  }))
})

// 计算默认选中项的索引
const defaultIndex = computed(() => {
  if (!props.modelValue || !formatColumns.value.length) return 0
  return formatColumns.value.findIndex((item) => item.value === props.modelValue)
})

watch(
  () => props.modelValue,
  (value) => {
    if (value) {
      const selectedOption = formatColumns.value.find((item) => item.value === value)
      if (selectedOption) {
        fieldValue.value = selectedOption.text
      }
    } else {
      fieldValue.value = ''
    }
  },
  { immediate: true }
)

const showPickerClick = () => {
  if (props.columns.length === 0) {
    showToast('暂无数据')
    return
  }
  showPicker.value = true
}

const onConfirm = (value) => {
  showPicker.value = false
  console.log(value)

  if (value.selectedOptions) {
    // 处理性别选择等场景
    const selectedOption = value.selectedOptions[0]
    fieldValue.value = selectedOption.text
    emit('update:modelValue', selectedOption.value)
    emit('change', selectedOption)
  } else {
    // 处理城市选择等场景
    fieldValue.value = value.text
    emit('update:modelValue', value.value)
    emit('change', value)
  }
}
</script>
  
<style scoped>
.ipicker :deep(.van-icon-arrow:before){
  position: relative;
  top: 5px;
  right: 5px;
  transform: rotate(90deg);
  color: #999;
}
</style>